/*
 *	Perlin Production Co. Ltd. September 2012 (c).
 *			euclid.c
 *		
 */
#include "WinGDI.h"

#define _DEBUG	0
 
unsigned EComp(_x1,_x2)
char	_x1;
char	_x2;
{
	unsigned result;
	result = _x2-_x1;
	result *= result;
	if (result > 0x5555) result = 0x5555; /* far enough, or use long arith */
	return result;
}


/*
	Euclidian distance
	
	(r1-r2)*(r1-r2)+(g1-g2)*(g1-g2)+(b1-b2)*(b1-b2)
*/

unsigned EDist(_rgb1, _rgb2)
RGB	*_rgb1;
RGB	*_rgb2;
{
	unsigned r,g,b;
	unsigned result;
	
	r = EComp(_rgb1->rgbRed   , _rgb2->rgbRed);
	g = EComp(_rgb1->rgbGreen , _rgb2->rgbGreen);
	b = EComp(_rgb1->rgbBlue  , _rgb2->rgbBlue);
	
	return r + g + b;
}	



Euclid(_rgb, _rgb888)
RGB		*_rgb;
RGB		*_rgb888;
{
	RGB		*rgb;
	unsigned	d, dmin;
	int	 	i;
/*	
	if (_rgb->rgbBlue || _rgb->rgbGreen || _rgb->rgbRed)
	{
*/		
		rgb	= 0;
		dmin	= ~0;
			
		for ( i = 0; i < 0x100; ++i, ++_rgb888)
		{
			if (!_rgb888->rgbReserved)
			{
				d = EDist(_rgb,_rgb888);
				if (d <= dmin)
				{
					dmin	= d;
					rgb	= _rgb888;
				}
			}
		}
		if (!rgb) trouble("Euclidian metric search failed",0);
	
		rgb->rgbReserved = 1; /* color is reserved */
		CpyRGB(_rgb,rgb);
/*		
	}
*/	
}





char Euc233(_rgb, _rgb888)
RGB		*_rgb;
RGB		*_rgb888;
{
	RGB	rgb;
	
	CpyRGB(&rgb, _rgb);
/*
	_rgb->rgbBlue	= ClrSHL(_rgb->rgbBlue);
	_rgb->rgbGreen	= ClrSHL(_rgb->rgbGreen);
	_rgb->rgbRed	= ClrSHL(_rgb->rgbRed);	
*/	
	Euclid(&rgb, _rgb888);
	return Clr233(&rgb);
}
